var isSocketOff = true;

function buildWebSocket() {
    var wsClient = new WebSocket('ws://172.18.8.69:9875/wsRobot');//121.33.231.74:4180
    window.myWSClient = wsClient;
    //连接
    wsClient.open = function (e) {
        el.value += "连接到了！\r\n";
        isSocketOff = false;
        alert("OK");
    }
    wsClient.onclose = function (e) {
        el.value += "突然你就走了，断开了！\r\n";
        isSocketOff = true;
    }
    //接收
    wsClient.onmessage = function (e) {
        var edata = e.data;
        loadJSON(JSON.parse(edata));
    }
    wsClient.onerror = function (e) {
        el.value += "连接失败！结果：" + e.data + "\r\n";
    }
}
function sendData(msg) {
    if (isSocketOff) {
        buildWebSocket();
        setTimeout(() => {
            myWSClient.send(msg);
        }, 100);
    }
    else {
        myWSClient.send(msg);
    }
}
function getFirstNode() {

    // 改用内嵌模态框，避免丑陋弹窗
    const modal = document.createElement('div');
    modal.innerHTML = `
      <div style="position:fixed;inset:0;background:rgba(0,0,0,.4);display:flex;align-items:center;justify-content:center;z-index:9999">
        <iframe src="forms/selectFirstNode.html" style="width:500px;height:400px;border:none;border-radius:8px;background:#fff"></iframe>
      </div>`;
    document.body.appendChild(modal);
    // 点击遮罩关闭
    modal.addEventListener('click', e => {
        if (e.target === modal) document.body.removeChild(modal);
    });

    // 监听 iframe 内部 postMessage 消息
    window.addEventListener('message', function handleMsg(ev) {
        // 只接受来自我们 iframe 的消息
        if (ev.origin !== window.location.origin) return;
        // 约定数据格式：{action:'selectNode', nodeId:'xxx'}
        if (ev.data == "close") {
            document.body.removeChild(modal);
            // 移除一次性监听
            window.removeEventListener('message', handleMsg);
            return;
        }
        if (ev.data) {
            // 拿到选中节点 id 后发送请求
            sendData('getFirstNode:' + JSON.stringify(ev.data));
            // 关闭模态框
            document.body.removeChild(modal);
            // 移除一次性监听
            window.removeEventListener('message', handleMsg);
        }
    });
}
function getNextNodes(id) {
    if (!id) { id = window.globel.lastMouseHoverNode.id; }
    let json={
        entityId:id
    }
    sendData("getNextNode:" + JSON.stringify(json));
}